<template>
  <div>
    <div class="imgbox"><img src="../../src/assets/musiclogo.png" alt="" /></div>
    <!-- 表单 -->
    <van-form>
      <!-- 通过 pattern 进行正则校验 -->
      <van-field v-model="phone" maxlength="11" type="tel" label="手机号" placeholder="输入手机号码" @input="checkPhone" :error-message="phoneStatus" />
      <!-- 通过 validator 进行函数校验 -->
      <van-field v-model="password" label="密码" type="text" maxlength="16" placeholder="密码" />
      <!-- 通过 validator 进行异步函数校验 -->
      <div style="margin: 16px">
        <van-button round block type="danger" native-type="submit" @click="LogoHandel">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      active: 3,
      phone: '',
      password: '',
      phoneStatus: '',
    }
  },
  methods: {
    // 校验函数返回 true 表示校验通过，false 表示不通过
    checkPhone(val) {
      let phoneRex = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (phoneRex.test(val)) {
        this.phoneStatus = ''
      } else {
        this.phoneStatus = '手机格式不正确'
        return false
      }
    },
    LogoHandel() {
      let newDate = new Date().getTime()
      console.log(this.phone || this.password, this.phone)
      if (this.phone === '') {
        this.$toast('请输入手机号')
        return false
      }
      if (this.password === '') {
        this.$toast('请输入密码')
        return false
      }
      this.http.post(`/login/cellphone?phone=${this.phone}&password=${this.password}&timestamp=${newDate}`, { withCredentials: true }).then((res) => {
        if (res.data.code !== 200) {
          this.$toast('手机号或密码错误！')
        } else {
          console.log(res.data)
          this.$toast.success('登录成功！')
          window.localStorage.setItem('token', res.data.token)
          window.localStorage.setItem('userId', res.data.profile.userId)
          window.localStorage.setItem('cookie', res.data.cookie)
          //登录成功后跳转
          this.$router.push('/home')
        }
      })
      // this.http.post("/user/detail?uid=83764524").then((res) => {
      //   console.log(1111111111111111111, res, res.data);
      // });
    },
  },
}
</script>

<style scoped>
.imgbox {
  text-align: center;
  margin: 100px 0;
}
</style>
